package cn.wolfcode.listener;

import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMQResult;
import cn.wolfcode.server.WebSocketServer;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RocketMQMessageListener(
        consumerGroup = "OrderMQResultListener",
        topic = MQConstant.ORDER_RESULT_TOPIC
)
public class OrderMQResultListener implements RocketMQListener<OrderMQResult> {
    @Override
    public void onMessage(OrderMQResult orderMQResult) {
        // 睡一秒, 方便客户端和WebSocket建立连接
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String token = orderMQResult.getToken();
        WebSocketServer webSocketServer = WebSocketServer.clients.get(token);
        try {
            webSocketServer.getSession().getBasicRemote().sendText(JSON.toJSONString(orderMQResult));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
